﻿using ManaMaple.Auth.Helpers;
using ManaMaple.Kit.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Reflection.Emit;
using System.Text;
using System.Threading.Tasks;

namespace ManaMaple.Core.Attributes
{
    /// <summary>
    /// 过滤器
    /// </summary>
    public class CustomAuthorizationFilterAttribute : Attribute, IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationFilterContext context)
        {
            // 如果方法上面标记了AllowAnonymous特性，则跳过登录校验-以及权限检查
            if (context.ActionDescriptor.EndpointMetadata.Any(item => item is AllowAnonymousAttribute))
                return;
                
            var authHeader = context.HttpContext.Request.Headers["Authorization"].ToString();
            if (string.IsNullOrWhiteSpace(authHeader))
            {
                context.Result = new ContentResult()
                {
                    Content = JsonConvert.SerializeObject(ApiResponse.LoginExpired("此接口必须携带Token访问，请登录携带Token访问！")),
                    ContentType = "application/json;charset=utf-8",
                    StatusCode = StatusCodes.Status200OK
                };
                return; // 提前返回，避免继续执行
            }
            
            // 去掉Bearer字串
            authHeader = authHeader.Replace("Bearer", "").Trim();
            if (string.IsNullOrWhiteSpace(authHeader))
            {
                context.Result = new ContentResult()
                {
                    Content = JsonConvert.SerializeObject(ApiResponse.LoginExpired("Token验证失败：您没有权限调用此接口，请登录重新获取Token")),
                    ContentType = "application/json;charset=utf-8",
                    StatusCode = StatusCodes.Status200OK
                };
                return; // 提前返回，避免继续执行
            }
            
            // 此处authHeader已经过验证，不为空
            var payload = JwtHelper.Decode(authHeader);
            if (payload.ValidTo < DateTime.UtcNow)
            {
                context.Result = new ContentResult()
                {
                    Content = JsonConvert.SerializeObject(ApiResponse.LoginExpired("Token已过期，请登录重新获取Token")),
                    ContentType = "application/json;charset=utf-8",
                    StatusCode = StatusCodes.Status200OK
                };
            }
        }
    }
}
